/*
Copyright (c) 2012, 2013 Regents of the University of California
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions 
are met:

 - Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
 - Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the
   distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
OF THE POSSIBILITY OF SUCH DAMAGE.
*/

function analysisRadio(refresh){
	getTimeRange();
	if (typeof refresh == 'undefined'){
		var refresh = false
	}
	if (document.getElementById("analysisRadio2").checked){
		$('#avgDay').removeAttr('disabled')
		$('#iesna').show()
		$('#analysisOptionsIEQ').hide()
		$('#smoothGroup').show()
		$('#hooDiv').show()
		if (!refresh){
			$('#analysisOptions').html('<h6>Options</h6><div class="controls" id="ctRadioDiv"><label class="radio"><input type="radio" name="ctRadio" id="ctRadioLine" checked>Line chart</label><label class="radio"><input type="radio" name="ctRadio" id="ctRadioBoxplot" value="bp">Boxplot chart</label><label class="radio"><input type="radio" name="ctRadio" id="ctRadioMap" value="cc">Map chart</label></div><h6>Note:</h6><p style="font-size: 11px">The start time you select must be after the start time of a defined device instance (test) in order to be included in the chart.</p>')
		}
		mapColumnLAI();
		$('#ctRadioDiv input:radio').change(function(){
				mapColumnLAI();
			});
		analysisType = 'lightingLT'
		var stratDevice = 'none'
		buildTree(analysisType, stratDevice);
	}
	else {
		$('#analysisOptionsFlr').hide()
		$('#iesna').hide()
		$('#smoothGroup').show()
		$('#hooDiv').show()
		analysisType = 'lighting_model'
		var stratDevice = 'none'
		if (!refresh){
			$('#analysisOptions').html('<h6>Options</h6><div class="controls" id="ctRadioDiv"><label class="radio"><input type="radio" name="ctRadio" id="ctImRadioStackedBar" checked>Stacked bar chart</label><label class="radio"><input type="radio" name="ctRadio" id="ctImRadioMap">Map chart</label></div>')
		}
		$('#ctRadioDiv input:radio').change(function(){
	    	mapColumnLAI()
		});
		mapColumnLAI()
	}
}

function lightingChart(data){
    if ($('#ctRadioMap').is(':checked')){
    	$('#chart').html(data)
    	$('#chartContainer').attr('class', 'span7');
    }
    else{
	    //generate a list of all the light levels to use for computing %over or under IESNA level
		ll_all = [];
		for (var i=0; i < data.data.length; i++){
			for (var j=0; j < data.data[i].data.length; j++){
				if (data.type == 'boxplot'){
					ll_all = ll_all.concat(data.data[i].data[j][2])
				}
				else if (data.type == 'splineAvgDay'){
					ll_all = ll_all.concat(data.data[i].data[j])
				}
				else {
					ll_all = ll_all.concat(data.data[i].data[j][1])
				}
				
			}
			if (data.type == 'boxplot'){i++;} //skip the scatter data series
		}
    	$('#chartContainer').attr('class', 'span8');
    	$('#legend').html('');
	    if (data.type == 'spline'){
	    	chart1 = new Highcharts.Chart({
		         chart: {
		            renderTo: 'chart',
		            zoomType: 'xy',
		         },
		         title: {
		            text: ' '
		         },
		         xAxis: {
				   type: 'datetime',
		     	   title: {
		           text: ''
		            }
		         },
		         yAxis: {
		            title: {
		               text: 'Illuminance (fc)'
		            },
		         },
		         plotOptions: {
		         	spline: {
	                marker: {
	                    enabled: false,
	                    states: {
	                        hover: {
	                            enabled: true,
	                        }
	                    }
	                },
	               }
	             },
		         credits: {enabled: false},
		         series: data.data,
		      });
	    }
	    else{
			if (data.categories.length < 1){alert('No valid data for this time range.'); $('#chart').unblock(); return;}
			if (data.alert == true){alert('The time period you selected resulted in too many entries to display. Only the first 24 entries are shown.')}
			if (data.categories.length > 8){label_style = {rotation: -55, align: 'right'}}
			else {label_style = {}}
			chart1 = new Highcharts.Chart({
		         chart: {
		            renderTo: 'chart',
		            zoomType: 'xy',
		         },
		         title: {
		            text: ' '
		         },
		         xAxis: {
		           categories: data.categories,
		     	   labels: label_style,
		     	   title: {
		           text: ''
		            }
		         },
		         yAxis: {
		            title: {
		               text: 'Illuminance (fc)'
		            },
		         },
		         credits: {enabled: false},
		         series: data.data,
		      });
	    }
	lightingLimit();
	}
   $('#chart').unblock()
}

function analysisPlot(){
	$('#chartImageCheck').removeAttr("checked") //reset save image check
	$('#chartImageSave').hide();
	//block chart overlay
	$('#chart').block({ 
		css: { 
			border: 'none', 
		    padding: '15px', 
            backgroundColor: '#002e48', 
            '-webkit-border-radius': '10px', 
            '-moz-border-radius': '10px', 
            opacity: .75, 
            color: '#fff' 
        }
    });
    
    //get start and end time in milliseconds since epoch UTC
	getTimeRange();
	var wkd = document.getElementById("wkdays").checked;
	var sh = Number(document.getElementById("startHour").value);
	var eh = Number(document.getElementById("endHour").value);
	var ad = document.getElementById("alldays").checked;
    
    //setup data to send to django side
    treeSelection().done(function(params){
		params['start_time'] = global_start
		params['end_time'] = global_end
		params['wkd'] = wkd
		params['sh'] = sh
		params['eh'] = eh
		params['projectId'] = sessvars.sessionObj['projectId']
		params['resample_s'] = $('#resampleTime').val();
		params['ad'] = ad
		if (document.getElementById("avgDay").checked){ var avg_day = true; }
		else{var avg_day = false;}
		if (document.getElementById("analysisRadio2").checked){
			if ($('#ctRadioLine').is(':checked')){
				if (avg_day){params['chart_type'] = 'splineAvgDay';}
				else {params['chart_type'] = 'spline';}
			}
			else if ($('#ctRadioMap').is(':checked')){
				params['chart_type'] = 'map_lighting'
				params['conditions'] = $('#iesnaSelect').find("option:selected").val() * 1;
				params['floor'] = $('#id_floor').val()
			}
			else{ //boxplot
				if (avg_day){params['chart_type'] = 'boxplotAvgDay';}
				else {params['chart_type'] = 'boxplotLT';}
			}
		}
		else if (document.getElementById("analysisRadio3").checked){
			params['ieq_model'] = $('form#ieqModelForm').serializeObject()
			params['save_model'] = document.getElementById("saveIeqModel").checked;
			//params['ieq_save'] = $('form#ieqSaveForm').serializeObject()
			params['time_length'] = 'lt'
			if ($('#ctImRadioStackedBar').is(':checked')){
				params['chart_type'] = 'bar'
			}
			else{
				params['chart_type'] = 'ieq_map'
				params['floor'] = $('#id_floor').val()
			}
		}
		params['analysisType'] = analysisType
	 
		$.ajax({
			type: "POST",
			url: "/pmp/lighting/",
			data: JSON.stringify(params),
			datatype: "json",
			success: function(data){					
				if (document.getElementById("analysisRadio3").checked){
					if ($('#ctImRadioStackedBar').is(':checked')){ieqModelChart(data);}
					else{$('#chart').html(data);}
				}
				else {lightingChart(data);}
				$('#chartImage').show();			
			}
		});
	});
}

function lightingLimit(){
	var lightLevel = $('#iesnaSelect').find("option:selected").val() * 1;
	$('#legend').html('')
	if (typeof chart1 != 'undefined'){
		if (typeof chart1.yAxis[0].plotLinesAndBands[0] != 'undefined'){chart1.yAxis[0].removePlotBand('pb-1');}
		if (lightLevel > 0){
			
			chart1.yAxis[0].addPlotBand({
                color: '#ffdddd',
                from: 0,
                to: lightLevel,
                id: 'pb-1'
            })
    	}
		var p_under = 0;
        var p_over = 0;
        for (var i=0; i < ll_all.length; i++){
        	if (ll_all[i] < lightLevel && typeof ll_all[i] != 'undefined'){p_under++;}
        	else {p_over++;}
        }
        p_under_f = Number(p_under / (p_under+p_over) * 100).toFixed(1)
        p_over_f = Number(p_over / (p_under+p_over) * 100).toFixed(1)
        $('<div style="font-size: 11px">>= the IESNA recommendation: ' + p_over_f + '%<br>< the IESNA recommendation: ' + p_under_f + '%</div>').css( {'font-weight': 'bold'}).appendTo("#legend").fadeIn(200);

	}
}
